import shutil

from django.test import TestCase
from dingxiang_doctor.utils.myredis import r
import os
import uuid
import time

# Create your tests here.
file_list = r.zset_zrangebyscore("file_time", 0, time.time() - 1800)
print(file_list)
for i in file_list:
    file_name = i.decode()
    file_size = r.zset_zscore("file_size", file_name)
    file_path = "../static/upload/" + file_name
    print(file_path)
    print(os.path.exists("../static/upload/4963100882267803649LINKDATA0.BIN"))
    if os.path.exists(file_path):
        total_size = 0
        for dirpath, dirnames, filenames in os.walk(file_path):
            for f in filenames:
                fp = os.path.join(dirpath, f)
                if os.path.exists(fp):
                    total_size += os.path.getsize(fp)
        # 获取文件数量
        file_number = sum(f.is_file() for f in os.scandir(file_path))
        if total_size == file_size:
            print("开始合并")
            fname = uuid.uuid4().hex
            arr = file_name.split(".")
            # 合并
            with open(f'static/upload/{fname}.{arr[-1]}', 'wb') as f:
                for i in range(int(file_number)):
                    with open(f'static/upload/{file_name}/{i}', 'rb') as f1:
                        f.write(f1.read())
        # 删除临时文件夹
        if os.path.exists(file_path):
            shutil.rmtree(file_path)

    # 删除redis中记录
    r.zset_zrem("file_time", f"{file_name}")
    r.zset_zrem("file_size", f"{file_name}")
